#include "vxWorks.h"
#include "stdlib.h"
#include "string.h"
#include "taskLib.h"
#include "smObjLib.h"
#include "errnoLib.h"
#include "intLib.h"
#include "eventLib.h"
#include "unistd.h"
#include "time.h"
#include "stdio.h"
#include "objLib.h"
#include "wdLib.h"
#include "msgQLib.h"
#include "private/distObjTypeP.h"
#include "ioLib.h"
typedef int s32;
typedef unsigned int u32;
typedef unsigned char u8;

#define sleep(timeO) taskDelay (timeO * (sysClkRateGet())) /* macro */

#define PIPE_NAME "pipe"

#define MAX_PIPE_MSGS 10
#define MAX_PIPE_LENGTH 512

#define STK_SIZE 5000  
#define WRITE_PRORITY 102
#define READ_PRORITY 202
#define OPTIONS 0

#define HEAP 1
#define STR 0

LOCAL s32 pipe_fd;

void task_pipe_write(void)
{
    u32 err=0;
    char data[]="pipe message\n";   
    u32 val=0x30;
    FOREVER
    {    
  #if STR
       write(pipe_fd, data, sizeof(data));       
       printf("send %s\n", data);
  #else 
       write(pipe_fd, (char *)&val, sizeof(u32));      
       printf("send %x\n", val);
  #endif     
       sleep(3);
    }
}

void task_pipe_read(void)
{
    u32 err=0;
 #ifndef HEAP   
    char recv[MAX_PIPE_LENGTH]={0};
 #endif   
     FOREVER
     {
     #if HEAP
        char *recv=(char *)calloc(1, sizeof(char)*MAX_PIPE_LENGTH);
         if(NULL == recv)
            break;   
      #endif      
          err = read(pipe_fd, recv,MAX_PIPE_LENGTH);
          printf("recv bytes %d\n", err);
          {
 #if STR         
            printf("recv %s\n", recv);
 #else
            printf("recv %x\n", *recv);
 #endif           
          }
      #if HEAP   
          cfree(recv);
      #endif    
          sleep(3);
     }
 
}

void pipe_init()
{ 
    u32 err =0;
    err = pipeDevCreate(PIPE_NAME, MAX_PIPE_MSGS, MAX_PIPE_LENGTH);
    if(0 != err)
    {
        printf("pipe create failed\n");
    }
}

void pipe_open()
{
    pipe_fd = open(PIPE_NAME,  O_RDWR,0644); 
	if (0 == pipe_fd)
	{
		perror("open file");
		exit(1);
	}
}

s32 pipe(void)
{
    u32 write_id;
    u32 read_id;
    pipe_init();
    pipe_open();
    write_id = taskSpawn("write", WRITE_PRORITY, OPTIONS, STK_SIZE,(FUNCPTR)task_pipe_write,0,0,0,0,0,0,0,0,0,0);
    
    read_id = taskSpawn("read", READ_PRORITY, OPTIONS, STK_SIZE,(FUNCPTR)task_pipe_read,0,0,0,0,0,0,0,0,0,0);
    printf("write task id %x\t read task id %x\n", write_id, read_id);
    return 0;
}


